import sun.misc.Unsafe;
import sun.reflect.Reflection;

import java.lang.reflect.Field;

/**
 * @author Created by chenxin34 on 2019/3/3 下午6:24.
 */
public class UnsafeTest {
    public static void main(String[] args) {
        testUnsafePutAndNormalSet();
    }

    private static void testUnsafePutAndNormalSet() {
        int size = 10000000;
        byte[] a = new byte[size];
        for (int i = 0; i < 10000; i++) {
            a[i] = (byte) i;
        }

        long start = System.currentTimeMillis();
        for (int i = 0; i < size; i++) {
            a[i] = (byte) i;
        }
        long end = System.currentTimeMillis();
        long cost = end - start;
        System.out.println("cost = " + cost);

        Unsafe unsafe = getUnsafe();
        long startB = System.currentTimeMillis();
        long base = unsafe.arrayBaseOffset(a.getClass());
        for (int i = 0; i < size; i++) {
            unsafe.putByte(a, base + i, (byte) i);

        }
        long endB = System.currentTimeMillis();
        long costB = endB - startB;
        System.out.println("costB = " + costB);
    }

    private static void testByteSet() {
        byte[] a = new byte[3];
        byte[] b = new byte[4];
        a[1] = 8;
        b[2] = 3;
        System.out.println(a[1]);
        System.out.println(b[2]);
        Unsafe unsafe = getUnsafe();
        int base = unsafe.arrayBaseOffset(a.getClass());
        System.out.println(base);
        long offset = base + 1;
        byte xxx = 9;
        unsafe.putByte(a, offset, xxx);
        System.out.println("after unsafe set a[1] = " + a[1]);

        long baseB = unsafe.arrayBaseOffset(b.getClass());
        byte yyy = 10;
        unsafe.putByte(b, baseB + 2, yyy);
        System.out.println("after unsafe set b[2] = " + b[2]);
    }

    private static Unsafe getUnsafe() {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            return (Unsafe) field.get(null);
        } catch (Exception e) {
            throw new RuntimeException("unsafe is null");
        }
    }
}
